package cn.com.infcn.monitor.task.jvm.impl;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryManagerMXBean;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.jvm.bean.IFCJVMMemoryManager;
import cn.com.infcn.monitor.task.impl.BaseTask;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;

/**
 * 内存管理器的管理接口。
 * 
 * 内存管理器管理 Java 虚拟机的一个或多个内存池。
 * 
 * @author jjs
 *
 */
public class JVMMemoryManagerTask extends BaseTask {

	private final static Logger logger = LoggerFactory.getLogger(JVMMemoryManagerTask.class);

	public JVMMemoryManagerTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {
		IFCResponseBean result = jvmMemoryManager();
		sendResponse(result);
	}

	public IFCResponseBean jvmMemoryManager() {
		IFCResponseBean result = new IFCResponseBean();

		List<IFCJVMMemoryManager> ifcMemoryManagers = null;

		MBeanServerConnection mbs = null;
		try {
			// 获取MBeanServerConnection
			mbs = MBeanServerConnectionFactory.getInstance(IFCMinitorConstanst.JMXURL);
		} catch (IOException e) {
			logger.error("jmx.url 连接异常！" + e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg("jmx.url 连接异常！");
			return result;
		}

		try {

			ObjectName mmName = new ObjectName(ManagementFactory.MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE + ",*");

			Set<ObjectName> mbeans = mbs.queryNames(mmName, null);
			if (mbeans != null) {
				IFCJVMMemoryManager ifcMemoryManager = null;
				ifcMemoryManagers = new ArrayList<IFCJVMMemoryManager>();

				Iterator<ObjectName> iterator = mbeans.iterator();
				while (iterator.hasNext()) {
					ObjectName objName = iterator.next();
					MemoryManagerMXBean mm = ManagementFactory.newPlatformMXBeanProxy(mbs, objName.getCanonicalName(),
							MemoryManagerMXBean.class);

					ifcMemoryManager = new IFCJVMMemoryManager();
					ifcMemoryManager.setMemoryPoolNames(mm.getMemoryPoolNames());
					ifcMemoryManager.setName(mm.getName());

					ifcMemoryManagers.add(ifcMemoryManager);
				}
			}

			result.setResult(ifcMemoryManagers);
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);

		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		JVMMemoryManagerTask task = new JVMMemoryManagerTask(null, null);
		IFCResponseBean result = task.jvmMemoryManager();
		List<IFCJVMMemoryManager> ifcMemoryManagers = (List<IFCJVMMemoryManager>) result.getResult();

		for (IFCJVMMemoryManager ifcjvmMemoryManager : ifcMemoryManagers) {
			String[] names = ifcjvmMemoryManager.getMemoryPoolNames();
			if (names != null) {
				for (String str : names) {
					System.out.print(str + "\t");
				}
			}
			System.out.println();
			System.out.println(ifcjvmMemoryManager.getName());
		}
	}

}
